#include     <stdio.h>
#include     <stdlib.h> 
#include     <unistd.h>  
#include     <sys/types.h>
#include     <sys/stat.h>
#include     <sys/ioctl.h>
#include     <fcntl.h> 
#include     <termios.h>
#include     <errno.h>
#include     <string.h>
#include <signal.h>
#include "iNEMO_SDK.h"
#include "ComConfig.h"

#define     MAXLINE     256

static void my_exit( int );
int         fd;

int main()
{
    int i;
    int len;
    int n = 0;      
    char read_buf[ MAXLINE ];
    char write_buf[ MAXLINE ];
    struct termios opt; 

    fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY );    //默认为阻塞读方式
    if(fd == -1)
    {
        perror("open serial 0");
        exit(0);
    }
    
    signal(SIGINT, my_exit);

    set_speed(fd, 115200);
    set_Parity(fd, 8, 1, 'N'); 
    setVtimeVmin( fd, 1, 60, NULL, NULL);

    printf("start send and receive data\n");

    char connect[] = { 0xaa, 0x20, 0x01, 0x00, 0xaa };
    char setoutput[] = { 0xaa, 0x20, 0x05, 0x50, 0x00, 0x00, 0x00, 0x00, 0xaa };
    char getoutput[MAXLINE];
    int count = MAXLINE;

    
    INEMO_SendFrameBase( fd, connect, 5, getoutput, &count );
    printf("hoho,count: %d\n", count );
    count = MAXLINE;
    INEMO_SendFrameBase( fd, setoutput, 9, getoutput, &count ); 
    if( count == 3 )
        printf("hoho,3\n");
        

    if( 0 == INEMO_Start_Acquision( fd ) )
        printf("hoho,chengogng: \n");
    
    int cnt = 0;
    while(1)
    {    
        cnt++;
        count = read( fd, getoutput, 52 );
        fprintf(stderr, "%d,read %d bytes\n",cnt , count );
        for( i = 0; i < count; ++i ) 
            printf( "%2X ", (unsigned char)*(getoutput+ i) );
        printf("\n");

    }
}

static void my_exit( int signo )
{
    char stopAcquision[] = { 0xaa, 0x20, 0x01, 0x53, 0xaa };
    char disconnect[] = { 0xaa, 0x20, 0x01, 0x01, 0xaa };
    write( fd, stopAcquision, 5 );
    //write( fd, disconnect,    5 );
    tcflush( fd, TCIOFLUSH );
    printf("clean have done\n");

    exit(1);
}
